//
//  SortableController+Gesture.swift
//
//  Created by 谢强 on 15/03/2018.
//  Copyright © 2018 谢强. All rights reserved.
//

import UIKit

// MARK: - 手势
extension SortableController {
    
    /// 处理长按手势
    @objc func handleLongPressGesture(gesture: UIGestureRecognizer) {
        
        guard let superview = tableView?.superview else { return }
        
        let touchPoint = gesture.location(in: superview)
        
        switch gesture.state {
        case .began:
            // 开始
            beginReorder(startPoint: touchPoint)
            
        case .changed:
            // 更新
            updateReorder(changedPoint: touchPoint)
            
        case .ended, .cancelled, .failed, .possible:
            // 结束
            endReorder()
        }
    }
}

// MARK: - 系统手势
extension SortableController: UIGestureRecognizerDelegate {
    
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        
        guard let tableView = tableView else { return false }
        
        let touchPoint = gestureRecognizer.location(in: tableView)
        guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return false }
        
        return delegate?.jw_tableView(tableView, isSortableAt: indexPath) ?? true
    }
}

